﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace game
{
    public class ParticleEmitter
    {
        public enum Type
        {
            POINT,
            LINE,
        }

        protected ParticleSystem particleSystem;

        protected Type type;

        public float EmitTimeMs { get; set; }

        protected Vector3 oldPosition;
        protected float emitTimeAccumMs = 0;

        protected float lineLength; // concerned when type = LINE

        public ParticleEmitter(ParticleSystem particleSystem, float emitTime, Vector3 initialPosition, float lineLength)
            : this(particleSystem, emitTime, initialPosition)
        {
            type = Type.LINE;
            this.lineLength = lineLength;
        }

        public ParticleEmitter(ParticleSystem particleSystem, float emitTime, Vector3 initialPosition)
        {
            this.particleSystem = particleSystem;
            this.EmitTimeMs = emitTime;
            this.oldPosition = initialPosition;

            type = Type.POINT;
        }


        public void Update(GameTime gameTime, Vector3 newPosition, Matrix rotation)
        {
            if (EmitTimeMs > 0.0f)
            {
                float currentTime = -emitTimeAccumMs;
                float elapsedTime = gameTime.ElapsedGameTime.Milliseconds;
                Vector3 position;

                emitTimeAccumMs += elapsedTime;

                while (emitTimeAccumMs >= EmitTimeMs)
                {
                    emitTimeAccumMs -= EmitTimeMs;
                    currentTime += EmitTimeMs;

                    float interp = currentTime / elapsedTime;
                    Vector3.Lerp(ref oldPosition, ref newPosition, interp, out position);

                    if (type == Type.LINE)
                    {
                        Vector3 up = Vector3.Up;
                        Vector3.Transform(ref up, ref rotation, out up);

                        Vector3 forward = Vector3.Forward;
                        Vector3.Transform(ref forward, ref rotation, out forward);

                        Vector3 offset;
                        Vector3.Cross(ref up, ref forward, out offset);

                        Vector3.Multiply(ref offset,
                            RandomHelper.RandomBetween(-1.0f, 1.0f) * lineLength,
                            out offset);

                        Vector3.Add(ref position, ref offset, out position);
                    }

                    particleSystem.AddParticle(position, currentTime - elapsedTime);
                }

            }
            oldPosition = newPosition;
        }
    }
}
